import { ref } from "vue";

import { http } from "../index";
import { IObject } from "@/types";
import { statusName } from "@/data";

function formatModel(model: any) {
  // delete model?.ID;
  delete model?.CreatedAt;
  delete model?.UpdatedAt;
  delete model?.DeletedAt;
  for (let key in model) {
    if (model[key] == null) {
      delete model?.[key];
    }
  }
  return model;
}

export function useModel(path: string) {
  let model = ref<IObject>();
  let connection = ref<any>({});

  async function getModel() {
    const result = (await http.post(`${path}/options`)).data;
    let { model: dtoModel, connection: dtoConnection } = result.data;
    model.value = formatModel(dtoModel);
    connection.value = dtoConnection ?? {};
    connection.value.Status = Object.entries(statusName).map(([k, v]) => {
      return {
        label: v,
        value: Number(k),
      };
    });
  }

  return {
    model,
    connection,
    getModel,
  };
}

export function useData(path: string) {
  const data = ref<IObject>({});

  async function find(id: string) {
    const res = (await http.get(`/${path}/${id}`)).data;
    data.value = res.data;
    return res?.msg;
  }

  async function create() {
    const res = (await http.post(path, data.value)).data;
    return res?.msg;
  }

  async function update(id: string) {
    const res = (await http.put(`/${path}/${id}`, data.value)).data;
    return res?.msg;
  }

  async function remove(id: string) {
    const res = (await http.delete(`/${path}/${id}`)).data;
    return res?.msg;
  }

  return {
    data,
    find,
    create,
    update,
    remove,
  };
}

export function usePageList(path: string) {
  let list = ref<Array<IObject>>([]);
  let total = ref(0);

  async function getPageList(
    size: number = 10,
    page: number = 1,
    order = "desc",
    sortName = "updated_at"
  ) {
    const res = (
      await http.post(`/${path}/page`, {
        page,
        size,
        order,
        sortName,
      })
    ).data;
    list.value = res.data.list.map((i: any) => formatModel(i));
    total.value = res.data.total;
    return res?.msg;
  }

  return {
    list,
    total,
    getPageList,
  };
}
